package com.mapforge.gui.tools;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.SpinnerNumberModel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import com.mapforge.gui.ClickableSlider;
import com.mapforge.map.tools.tilewriting.EraserTool;

/**
 * GUI control panel to manipulate a {@link EraserTool EraserTool's} size.
 * 
 * @see MapToolButton#setMapToolPanel(JPanel)
 * @author Will Morrison
 */
public class EraserToolControlPanel extends JPanel {
	/**
	 * Default serial version ID, here to remove warnings
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * Minimum value an {@link EraserTool} can have
	 */
	private static final int MIN = 1;
	/**
	 * Maximum value an {@link EraserTool} can have.
	 */
	private static final int MAX = 100;
	/**
	 * The {@link EraserTool} this panel represents.
	 */
	private EraserTool eraserTool;
	/**
	 * Slider used to manipulate this {@link EraserTool EraserTool's} size.
	 */
	private JSlider sliderSize;
	/**
	 * {@link SpinnerNumberModel} used by a {@link JSpinner} to manipulate this
	 * {@link EraserTool EraserTool's} size.
	 */
	private SpinnerNumberModel spnModel;

	/**
	 * Constructs a new {@link EraserToolControlPanel} with the specified
	 * {@link EraserTool EraserTool.}
	 * 
	 * @param eraserTool
	 *            specified {@link EraserTool}
	 */
	public EraserToolControlPanel(EraserTool eraserTool) {
		setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));

		this.eraserTool = eraserTool;
		spnModel = new SpinnerNumberModel(eraserTool.getSize(), MIN, MAX, 1);
		sliderSize = new ClickableSlider(JSlider.HORIZONTAL, MIN, MAX,
				eraserTool.getSize());
		JSpinner spnSize = new JSpinner(spnModel);

		sliderSize.setMinorTickSpacing(MAX / 4);
		sliderSize.setPaintTicks(true);
		this.add(new JLabel("Eraser Size", JLabel.CENTER), BorderLayout.NORTH);

		EraserChangeListener listener = new EraserChangeListener();
		spnModel.addChangeListener(listener);
		sliderSize.addChangeListener(listener);

		JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 2));
		panel.add(sliderSize);
		panel.add(spnSize);
		add(panel);
	}

	private class EraserChangeListener implements ChangeListener {
		@Override
		public void stateChanged(ChangeEvent e) {
			Object src = e.getSource();
			if (src == sliderSize) {
				spnModel.setValue(sliderSize.getValue());
			} else if (src == spnModel) {
				sliderSize.setValue(spnModel.getNumber().intValue());
			}
			eraserTool.setSize(sliderSize.getValue());
		}

	}

}
